package nmrworkflow.framework.gui;

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;

import nmrworkflow.framework.configuration.Preferences;
import nmrworkflow.framework.gui.FileChooser.Type;

public class PreferencesWindow extends JDialog
{
	private Preferences preferences;
	private FileChooser nmrPipe, showHdr, tmpDirectory;
	
	public PreferencesWindow(Preferences preferences)
	{
		this.preferences = preferences;
		
		nmrPipe = new FileChooser("NMRPipe", Type.File, preferences.getNmrPipePath());
		showHdr = new FileChooser("NMRPipe ShowHdr", Type.File, preferences.getShowHdrPath());
		tmpDirectory = new FileChooser("Temporary Directory", Type.Directory, preferences.getTempPath());
		
		super.setTitle("Preferences");
		super.setModal(true);
		super.add(components());
		super.pack();
	}
	
	private JPanel components()
	{
		JPanel components = new JPanel();
		JPanel spacer = new JPanel();
		spacer.setPreferredSize(new Dimension(150, 50));
		
		components.setLayout(new BoxLayout(components, BoxLayout.PAGE_AXIS));
		
		components.add(nmrPipe);
		components.add(showHdr);
		components.add(tmpDirectory);
		components.add(spacer);
		
		components.add(buttons());
		
		return components;
	}
	
	private JPanel buttons()
	{
		JPanel buttons = new JPanel();
		JButton ok = new JButton("OK");
		JButton cancel = new JButton("Cancel");
		final PreferencesWindow window = this;
		
		ok.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{
				Preferences preferences = window.getPreferences();
				
				preferences.setNmrPipePath(window.getNmrPipePath());
				preferences.setShowHdrPath(window.getShowHdrPath());
				preferences.setTempPath(window.getTempPath());
				
				// TODO: save
				
				window.dispose();
			}
		});
		
		cancel.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{	
				window.dispose();
			}
		});
		
		buttons.setLayout(new BoxLayout(buttons, BoxLayout.LINE_AXIS));
		buttons.add(ok);
		buttons.add(cancel);
		
		return buttons;
	}

	public Preferences getPreferences()
	{
		return preferences;
	}

	public void setPreferences(Preferences preferences)
	{
		this.preferences = preferences;
	}
	
	public File getNmrPipePath()
	{
		return this.nmrPipe.getPath();
	}
	
	public File getShowHdrPath()
	{
		return this.showHdr.getPath();
	}
	
	public File getTempPath()
	{
		return this.tmpDirectory.getPath();
	}
	
	public static void main(String[] args)
	{
		PreferencesWindow window = new PreferencesWindow(Preferences.getInstance());
		window.setVisible(true);
	}
}
